from common.ConfigReader import Reader
from httprunner import HttpRunner,Config,RunRequest,RunTestCase,Step
from business.login_test import TestLogin as Login      # 把登录文件导入过来，起一个别名，不然会识别成两条用例
"""
httprunner不支持for循环逻辑寻找
很多代码也比较冗余，通过charls抓包后还要自己改
对httprunner做二次封装
"""
base_path = Reader('config.ini').get_option('dev_base_url')

class API(HttpRunner):
    config = Config("start testing...").\
        base_url(base_path).\
        verify(False)
    teststeps = [
        Step(
            RunTestCase("登录").
                call(Login).
                export(*['token',])
        ),
    ]
"""
不同的网站都有不同的权限，比如说淘宝网，会有游客、用户、管理员、商家等等
"""
def reset_token(token=Login):       # 默认是管理员的账号
    # 通过token形参，来达到灵活切换不同的账号的目标
    API.teststeps.clear()       # 清空原来的token权限
    API.teststeps.append(
        Step(
            RunTestCase("登录").
                call(token).
                export(*['token',])
        )
    )
headers = {'Authori-zation': 'Bearer ${token}' }
def send_requests(api_name,method,path,body=None):
    if method =='post':
        return RunRequest(
            api_name
        ).\
            post(path).\
            with_headers(**headers).\
            with_json(body).\
            extract().\
            with_jmespath("body",'res_body')
    elif method =='get':
        return RunRequest(
            api_name
        ).\
            get(path).\
            with_headers(**headers).\
            extract().\
            with_jmespath("body",'res_body')
    elif method == 'delete':
        return RunRequest(
            api_name
        ).\
            delete(path). \
            with_headers(**headers). \
            extract(). \
            with_jmespath("body", 'res_body')
    elif method =='put':
        return RunRequest(
            api_name
        ).\
            put(path).\
            with_headers(**headers).\
            extract(). \
            with_jmespath("body", 'res_body')

def step_obj(obj):
    return Step(
        obj
    )

def get_last_response(step):
    API.teststeps.extend(step)      # 把所有的测试步骤加到teststeps列表
    obj = API()     # 实例化对象
    obj.test_start()    # 通过这个对象执行
    res = obj.with_export(['token','res_body']).get_export_variables()      # 导出所有取出的参数
    return res      # 返回






















